package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserServiceImpl userService;

    @Override
    public Result follow(Long followUserId, boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FOLLOW_KEY + userId;
        if(isFollow) {  // 1.关注
            // 1.1 新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if(isSuccess) {
                // 加入到redis集合：follows:userId = {关注userId这个用户的用户集合}
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
                return Result.ok();
            }
            return Result.fail("关注失败，请重试");
        }
        // 2.取消关注
        // 2.1删除数据
        boolean isSuccess = lambdaUpdate().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId).remove();
        if(isSuccess) {
            // 2.2从redis集合中删除
            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            return Result.ok();
        }
        return Result.fail("取消关注失败，请重试");
    }

    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        boolean exists = lambdaQuery().eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId).exists();
        return Result.ok(exists);
    }

    @Override
    public Result followCommons(Long id) {
        // 查询当前用户和给定用户共同关注的用户id集合
        Long currentUserId = UserHolder.getUser().getId();
        String key1 = RedisConstants.FOLLOW_KEY + currentUserId;
        String key2 = RedisConstants.FOLLOW_KEY + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if(intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 解析id集合
        List<Long> userIds = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 查询用户信息
        List<User> users = userService.listByIds(userIds);
        // 转换为DTO
        List<UserDTO> userDTOS = BeanUtil.copyToList(users, UserDTO.class);
        return Result.ok(userDTOS);
    }
}
